const STS = require('qcloud-cos-sts');

module.exports = class extends require('egg').Service {
  async selectAll() {
    const { ctx } = this;

    const res = await ctx.helper.query({ query: `select * from "meet_config"`, json: ['value'] });

    const data = {};
    res.forEach((r) => {
      data[r.key] = r.value;
    });
    return data;
  }
  async getVal(key) {
    const { ctx } = this;

    const res = await ctx.helper.query({ query: `select * from "meet_config" where key = '${key}'`, find: true, json: ['value'] });

    return res.value;
  }
  /** 腾讯云对象存储COS：获取临时密钥 */
  async sts() {
    const { ctx } = this;

    // 配置参数
    var config = {
      secretId: this.config.tencentCloud.secretId,
      secretKey: this.config.tencentCloud.secretKey,
      proxy: '',
      host: 'sts.tencentcloudapi.com', // 域名，非必须，默认为 sts.tencentcloudapi.com
      durationSeconds: 1800, // 密钥有效期
      // 放行判断相关参数
      bucket: 'meet-1258011420', // 换成你的 bucket
      region: 'ap-guangzhou', // 换成 bucket 所在地区
      allowPrefix: '*' // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
    };

    var shortBucketName = config.bucket.substr(0, config.bucket.lastIndexOf('-'));
    var appId = config.bucket.substr(1 + config.bucket.lastIndexOf('-'));
    var policy = {
      version: '2.0',
      statement: [
        {
          action: [
            // 简单上传
            'name/cos:PutObject',
            'name/cos:PostObject',
            // 分片上传
            'name/cos:InitiateMultipartUpload',
            'name/cos:ListMultipartUploads',
            'name/cos:ListParts',
            'name/cos:UploadPart',
            'name/cos:CompleteMultipartUpload'
          ],
          effect: 'allow',
          principal: { qcs: ['*'] },
          resource: ['qcs::cos:' + config.region + ':uid/' + appId + ':prefix//' + appId + '/' + shortBucketName + '/' + config.allowPrefix]
        }
      ]
    };
    const credential = await new Promise((resolve) => {
      STS.getCredential(
        {
          secretId: config.secretId,
          secretKey: config.secretKey,
          proxy: config.proxy,
          durationSeconds: config.durationSeconds,
          region: config.region,
          policy: policy
        },
        function (err, credential) {
          if (err) ctx.throw(500, err);
          resolve(credential);
        }
      );
    });

    return {
      ...credential,
      host: 'https://' + config.bucket + '.cos.' + config.region + '.myqcloud.com/'
    };
  }
};
